"""预设BOM差异表"""
from odoo import fields, models, api, _
from odoo.exceptions import UserError
from markupsafe import Markup


class PresetsBomDiff(models.Model):
    _inherit = 'sb.presets.bom.diff'

    sale_id = fields.Many2one('sale.order', string="销售单", related='presets_bom_id.sale_id', store=True)
    sale_order_line_id = fields.Many2one('sale.order.line', string="销售单行", related='sale_id.first_line', store=True)

    def check_requisition(self):
        self.ensure_one()
        action = self.env["ir.actions.act_window"]._for_xml_id('sb_base.action_s_product_lock')
        action['domain'] = [('sale_order_line_id', '=', self.sale_order_line_id.id), ('active', 'in', (True, False))]
        return action

    @api.model
    def create(self, vals):
        res = super().create(vals)
        # 创建完成,使用频道广播消息
        channel = self.env['discuss.channel'].sudo().search([('uuid', '=', 'M8u3JXyzQP')], limit=1)
        url = f"/web#id={res.id}&model={res._name}&view_type=form"
        if channel:
            msg = Markup(_(
                "<div style='color:orange;'>⚠️ <b>预设BOM生成差异</b></div>"
                "<div><b>%(name)s</b> 差异单号.</div>"
                "<div>please take note.</div>"
                "<div><a href='%(url)s' target='_blank'>📎 Click here to view the instruction</a></div>"
            ) % {'name': res.name, 'url': url})
            channel.sudo().message_post(
                body=msg,
                subject=_("预设BOM与JMI提交产生差异"),
                subtype_xmlid='mail.mt_comment',
                message_type="comment",
                author_id=self.env.user.partner_id.id,
            )
        return res
